<?php
namespace Home\Controller;
use Think\Controller;
class RefundController extends CommonController {

    /**
     * 售后列表
     */
	public function lists(){
        $uid = I('post.uid');
        if(!$uid) returnApiError(1,'uid参数错误');
	$refund = M('refund_return');
        $where['buyer_id'] = $uid;
        $pindex = I('post.pno', 1, 'intval');     //当前页码
        $psize = I('post.pgz', 10, 'intval');   //显示条数
         if (!$pindex)
            $pindex = 1;
        $pfirst = ($pindex - 1) * $psize;
        $field = 'refund_id,order_id,goods_name,refund_amount,order_sn,refund_sn,store_id,store_name,buyer_id,buyer_name,goods_id,goods_num as refund_num,goods_image,refund_type,seller_state,refund_state,return_type,add_time,seller_time,reason_id,reason_info,pic_info,buyer_message';
        $goods = M('order_goods');
        $goodsinfo = $goods->field("goods_id,goods_price,goods_num")->select();
        $refund_data = $refund->field($field)->where($where)->limit($pfirst .','.$psize)->select();
        if(!$refund_data){
            returnArr('数据为空');
        }
        foreach($refund_data as $k=>$v){
            $refund_data[$k]['goods_image'] = 'http://un-eagle.cn/data/upload/shop/store/goods/'.$refund_data[$k]['store_id'].'/'.$refund_data[$k]['goods_image'];
            $picarr = unserialize($v['pic_info']);
            $picarr = $picarr['buyer'];
            if($goodsinfo){
                foreach($goodsinfo as $info){
                    if($v["goods_id"]==$info["goods_id"]){ 
                        $refund_data[$k]['goods_price']=$info["goods_price"];
                        $refund_data[$k]['goods_num']=$info["goods_num"];
                    }
                }
            }
            foreach($picarr as $k2 => $v2){
                $picarr[$k2] = 'http://un-eagle.cn/data/upload/shop/refund/'.$v2;

            }
            $refund_data[$k]['pic_info'] =  array_values($picarr);
        }
        if($refund_data){
            returnApiSuccess('ok',$refund_data);
        }

	}

        /**
       * 申请售后
       */
	public function detail(){
        $orderid = I('post.orderid');
        if (!$orderid)
            returnApiError(1, '用户orderid参数错误');
            $model = M('order_goods');
            $rrmodel = M('refund_reason');
            $goods = C('DB_PREFIX').'order_goods';
            $order = C('DB_PREFIX').'order';
            $data = $model->field("$goods.*,$order.order_id,$order.order_sn,$order.store_id,$order.pay_sn,$order.buyer_id,$order.order_amount")->join("$order ON $goods.order_id = $order.order_id  and $order.order_id =$orderid")->find();
            $rrdata = $rrmodel->field("reason_id,reason_info")->order('reason_id desc')->select();
            $data['reason']=$rrdata;
            if(!$data){
                returnArr('数据为空');
            }else{
                returnApiSuccess('ok',$data);
            }
        }
       /**
       * 提交售后
       */
	public function insert(){
              //实例化
                $order = M('order');
                $orgdata = M('order_goods');
                $refund = M('refund_return');
                $goods = M('goods');
                $common = M("order_common");
                $reasons  = M("refund_reason");
                $data = array();
                //post 参数
                $orderid = I('post.orderid');
                if(!$orderid) returnApiError(1,'orderid参数错误');
                $goods_id = I('post.goods_id');
                if(!$goods_id) returnApiError(1,'goods_id参数错误');
                $refund_type = I('post.refund_type');
                $number =I('post.num');
                $is_check =I('post.is_check');
                $reason  =urldecode(I('post.buyer_message'));
                $status  = I('post.status');
                $reason_id = I('post.reason_id');
                $money = I('post.money');
                if(!$number){
                    $number = 1;
                }
                if(!$money) returnApiError(1,'金额参数错误');
                //订单商品
 
                $ogdata = $orgdata->field("goods_id as order_goods_id,goods_type as order_goods_type,goods_num")->where(array("order_id"=>$orderid,"goods_id"=>$goods_id))->find();
                if($number>$ogdata['goods_num'])returnApiError(1, '退款商品数量错误！');
                $gdata = $goods ->field("goods_id,goods_name,goods_image,goods_promotion_price")->where(array("goods_id"=> $goods_id))->find();
                $ordata = $order->field("order_id,order_sn,store_id,store_name,buyer_id,buyer_name,shipping_code")->where(array("order_id"=>$orderid))->find();
                $cdata = $common->field('shipping_express_id')->where(array("order_id"=>$orderid))->find();
                $status=1;
               if($status==1){
                $config = array(
                    'maxSize'    =>   3145728,
                    'rootPath'   =>   'web/data/upload/shop/refund/',
                    'savePath'   =>    '',
                    'saveName'   =>    array('date','YmdHis'),
                    'exts'       =>    array('jpg', 'gif', 'png', 'jpeg'),
                    'autoSub'    =>    false,
                );
                $ftpConfig     =    array(        
                   'host'     => '120.25.243.163', //服务器
                   'port'     => 21, //端口
                   'timeout'  => 90, //超时时间
                   'username' => 'userlisten', //用户名
                   'password' => 'sdfW2Q58i4W3a5Q6', //密码 
                   );
                    $upload = new \Think\Upload($config,'Ftp',$ftpConfig);// 实例化上传类
                    $info   =   $upload->uploads($_FILES);
                   if(!$info){
                       $error = $upload->getError();
                       if($error != '没有上传的文件！'){
                           returnApiError(1,$upload->getError());
                       }
                       /*if(!strstr($upload->getError(),"没有文件被上传")){
                          returnApiError(1,$upload->getError());
                        }*/
                   } 
                   $imgar = array();
                    foreach($info as $fname){
                       $imgar['buyer'][]= $fname['savename'];
                    }
               }
                $data = array_merge($ogdata,$gdata,$ordata,$cdata);
                $reasoninfo = $reasons ->field("reason_info")->where(array("reason_id"=>$reason_id))->find();
                if($reasoninfo){
                    $data['reason_info'] = $reasoninfo["reason_info"];
                }else{
                    $data['reason_info'] = "其它";
                }
               if($gdata["goods_promotion_price"]){
                   $maxM = $gdata["goods_promotion_price"]* $number;//退款金额
                   //echo 'money='.$money.'number='.$number.'price='.$gdata["goods_promotion_price"].'max='.$maxM;
                   if($money>$maxM) returnApiError(1,'超出退款金额！');
                   unset($gdata["goods_promotion_price"]);
                   $data ['refund_amount'] = $money;
               }
                $data["reason_id"] = $reason_id;
                $data ['refund_sn'] =  $this->getRefundsn($ordata["store_id"]);
                $data ["order_id"] =  $orderid;
                $data ["refund_type"] =  $refund_type;
                $data ["return_type"] =  $refund_type;
                $data ["goods_num"] =  $number;
                $data ["is_check"] = $is_check;
                $data ["order_lock"] =1;
                $data ["pic_info"] = serialize($imgar);            
                $data ["buyer_message"]  = $reason;
                $data ["add_time"] = time();
              
                if($lastInsId = $refund->add($data)){
                   // $order->where(array("order_id"=>$orderid))->setInc('lock_state', 1);
                   // $result = $model_order->editOrder($data,$condition);
                     returnApiSuccess('申请售后成功');
                 } else {
                     returnApiError(1,'数据写入错误！');
                 }
                
            
        }
            /**
            * IOS提交售后
            */
            public function iosinsert() {
            
              //实例化
              $order = M('order');
              $orgdata = M('order_goods');
              $refund = M('refund_return');
              $goods = M('goods');
              $common = M("order_common");
              $reasons  = M("refund_reason");
              $data = array();
              //post 参数
              $orderid = I('post.orderid');
              if(!$orderid) returnApiError(1,'orderid参数错误');
              $goods_id = I('post.goods_id');
              $refund_type = I('post.refund_type');
              if(!$goods_id) returnApiError(1,'goods_id参数错误');
              $number = I('post.num');
              $is_check = I('post.is_check');
              $reason = I('post.buyer_message');
              $reason_id = I('post.reason_id');
              $money = I('post.money');
                if(!$number){
                    $number = 1;
                }
                if(!$money) returnApiError(1,'金额参数错误');
              //订单商品
              $ogdata = $orgdata->field("goods_id as order_goods_id,goods_type as order_goods_type,goods_num")->where(array("order_id" => $orderid))->find();
              if ($number > $ogdata['goods_num'])
                  returnApiError(1, '退款商品数量错误！');
              $gdata = $goods->field("goods_id,goods_name,goods_image,goods_promotion_price")->where(array("goods_id" => $goods_id))->find();
              $ordata = $order->field("lock_state as order_lock, order_id,order_sn,store_id,store_name,buyer_id,buyer_name,shipping_code")->where(array("order_id" => $orderid))->find();
              $cdata = $common->field('shipping_express_id')->where(array("order_id" => $orderid))->find();

          
             // $path = dirname(dirname(dirname(dirname(dirname(__FILE__))))).'/data/upload/shop/refund/';
               $path  =  './Uploads/';
             // file_put_contents($path."file.txt",var_export($_POST["upfile"],TRUE));
              //if(!is_dir($path))returnApiError(1, '文件目录不存在！');
              $imgar = array();
              $files = $_POST['upfile'];
              if ($files) {
                  $is_true = false;
                    $config = array(
                    'hostname' => 'http://un-eagle.cn',
                    'username' => 'userlisten',
                    'password' => 'sdfW2Q58i4W3a5Q6',
                    'port' => 21
                    );
                    Vendor('Ftp.ftp');
                    $ftp = new \Ftp();
                    $ftp->connect($config);
                    for($i=0;$i<count($files);$i++){
                        
                        $byte = str_replace(' ', '', $files[$i]);   //处理数据
                        $byte = str_ireplace("<", '', $byte);
                        $byte = str_ireplace(">", '', $byte);
                        $byte = pack("H*", $byte);      //16进制转换成二进制
                        // file_put_contents('1.jpg',$byte);//写入文件中！
                        $fname = "br".rand(0,100).'ios_' . date("YmdHis") . '.png';
                        $imgar['buyer'][]= $fname;
                        $file = fopen($path . $fname, "w"); //打开文件准备写入
                        fwrite($file, $byte); //写入
                        fclose($file); //关闭
                        $ftp->delete_file('web/data/upload/shop/refund/'.$fname);
                        $upfile = $ftp->upload('./Uploads/'.$fname,'web/data/upload/shop/refund/'.$fname);
                        $is_true = true;
                        
                    }
              }
              if(!$is_true)returnApiError(1,'ftp上传失败');
              $data = array_merge($ogdata, $gdata, $ordata, $cdata);
                $reasoninfo = $reasons ->field("reason_info")->where(array("reason_id"=>$reason_id))->find();
                if($reasoninfo){
                    $data['reason_info'] = $reasoninfo["reason_info"];
                }else{
                    $data['reason_info'] = "其它";
                }
              if($gdata["goods_promotion_price"]){
                   $maxM = $gdata["goods_promotion_price"]* $number;//退款金额
                   if($money>$maxM) returnApiError(1,'超出退款金额！');
                   unset($gdata["goods_promotion_price"]);
                   $data ['refund_amount'] = $money;
               }
              $data["reason_id"] = $reason_id;
              $data ['refund_sn'] = $this->getRefundsn($ordata["store_id"]);
              $data ["order_id"] = $orderid;
              $data ["refund_type"] = $refund_type;
              $data ["return_type"] = $refund_type;
              $data ["goods_num"] = $number;
              $data ["is_check"] = $is_check;
              $data ["order_lock"] =1;
              $data ["pic_info"] = serialize($imgar);            
              $data ["buyer_message"] = $reason;
              $data ["add_time"] = time();

              if ($lastInsId = $refund->add($data)) {
                  // $order->where(array("order_id"=>$orderid))->setInc('lock_state', 1);
                  returnApiSuccess('申请售后成功');
              } else {
                  returnApiError(1,'数据写入错误！');
              }
          }

          public function getRefundsn($store_id) {
                $result = mt_rand(100,999).substr(100+$store_id,-3).date('ymdHis');
                return $result;
    }

    /**
     * 售后状态
     */
    public function refundstate(){
        $orderid = I('post.orderid');
        $goodsid = I('post.goodsid');
        $refund = M('refund');
        $where['order_id'] = $orderid;
        $where['goods_id'] = $goodsid;
        $data = $refund->where($where)->find();
        if($data){
            $state = 1;
        }else{
            $state = 0;
        }
        $arr = array(
            'is_refund' =>$state,
        );
        returnApiSuccess('ok',$arr);
    }
            
    public function refunddetail(){
        $refund_id = I("post.refund_id");
        //实例化
         $goods = M('order_goods');
         $refunds = M("refund_return");
         $express = M("express");
         $refundinfo = $refunds ->where(array("refund_id"=>$refund_id))->find();
            $picarr = unserialize($refundinfo['pic_info']);
            $picarr = $picarr['buyer'];
            foreach($picarr as $k2 => $v2){
            $picarr[$k2] = SHOP_SITE_URL.'/data/upload/shop/refund/'.$v2;

            }
            $refundinfo['pic_info'] =  array_values($picarr);
         $goodsinfo =  $goods->field("goods_id,goods_name,goods_image,goods_price,goods_num as buy_num")->where(array("order_id"=>$refundinfo["order_id"],"goods_id" => $refundinfo["goods_id"]))->find();
         $expressinfo = $express->where(array("e_state"=>'1',"e_order"=>'1'))->select();
            foreach($expressinfo as $express){
                if($refundinfo["express_id"]==$express["id"]){
                    $refundinfo["express_name"] =$express["e_name"];
                }
            }
         $data = array_merge($refundinfo,$goodsinfo); 
         $data ["express"] = $expressinfo;
            if(!$data){
                returnArr('数据为空');
            }else{
                returnApiSuccess('ok',$data);
            }
         
    }
    public function shippost(){
        $refund_id = I("post.refund_id");
        $express_id = I("post.express_id");
        $invoice_no = I("post.invoice_no");
        
        $refunds = M("refund_return");
        
        $condition = array();
       // $condition['seller_state'] = 2;
        //$condition['goods_state'] = 1;
        $condition['refund_id'] = $refund_id;
        $return  = $refunds->where($condition)->find();
        if($return['seller_state'] != 2){
            returnApiError(1,'商家未同意退货');
        }
        if(!empty($return)) {
            $refund_array = array();
            $refund_array['ship_time'] = time();
            $refund_array['delay_time'] = time();
            $refund_array['express_id'] = $express_id;
            $refund_array['invoice_no'] = $invoice_no;
            $refund_array['goods_state'] = '2';
            $state = $refunds->where(array("refund_id"=>$refund_id))->save($refund_array);
           if(!$state){
                returnApiError(1,'退款退货申请,发货保存失败');
            }else{
                returnApiSuccess("退款退货成功");
            }
        } else {
             returnApiError(1,'退货失败');
        }
        
        
    }
}